package org.example.redirect.console.runner;

import org.example.redirect.console.common.Util;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

@Component
@Order(1000)
public class FirstRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(String.format("FirstRunner, out=%s, err=%s", System.out, System.err));
        Util.toOut=System.out;
        Util.toErr=System.err;
        Util.dayStr=Util.getDayStr();
        File dir = new File("logs");
        if(dir.exists()==false) {
            dir.mkdirs();
        }
        Util.dirStr=dir.getAbsolutePath();
        Util.toFileOut=new FileOutputStream("logs\\console.out"+Util.dayStr, true);
        Util.toFileErr=new FileOutputStream("logs\\console.err"+Util.dayStr, true);
        System.setOut(new PrintStream(Util.toFileOut));
        System.setErr(new PrintStream(Util.toFileErr));
    }

    @Bean
    public ExitCodeGenerator exitCodeGenerator(){
        return () -> {
            System.setOut(Util.toOut);
            System.setErr(Util.toErr);
            try {
                Util.toFileOut.close();
                Util.toFileErr.close();
            } catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("getExitCode");
            return 0;
        };
    }
}
